package io.wdb.handler;

import java.nio.charset.Charset;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import io.wdb.config.AmqpConfig;

@Component
public class AmqpSendHandler {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    RabbitTemplate rabbitTemplate;

    public void sendTopic(String routineKey, String msg) {
        try {
            rabbitTemplate.convertAndSend(AmqpConfig.TOPIC_EXCHANGE, routineKey, msg.getBytes(Charset.forName("UTF-8")));
        }
        catch (AmqpException e) {
            logger.error(e.getMessage());
        }
        catch (Exception e) {
            logger.error(e.getMessage());
        }
    }


    // broadcast message
    // exchange - SERVICE_EXCHANGE
    public void sendFanout(String exchange, String msg) {
        logger.debug("sendFanout: " + exchange + " " + msg);
        try {
            MessageProperties props = new MessageProperties();
            Message message = new Message(msg.getBytes(Charset.forName("UTF-8")), props);
            rabbitTemplate.convertAndSend(exchange, "", message);
        }
        catch (AmqpException e) {
            logger.error(e.getMessage());
        }
        catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}

